import { useQuery } from '@tanstack/react-query';
import EventCenterServices from '@/api/services/eventCenterServices.ts';
import { useCatch } from '@/hooks';
import ITable, { ITableProps, ITableRef } from '@/components/Table';
import { MaintenancePlanInfo } from '#/entity.ts';
import MaintenancePlanServices, {
  MaintenancePlanListParams,
} from '@/api/services/maintenancePlanServices.ts';
import { FormFieldType } from '@ycx/ui';
import { Button, Space, Tooltip } from 'antd';
import { MaintenancePlanHandleStatus } from '#/enmu.ts';
import OrderServices from '@/api/services/workOrderServices';
import { Dayjs } from 'dayjs';
import PermissionGuard from '@/components/PermissionGuard';
import DetailDrawer, { DetailDrawerRef } from '@/pages/maintenancePlan/components/DetailDrawer.tsx';
import { useRef } from 'react';
import DelayModal, { DelayModalRef } from '@/pages/maintenancePlan/components/DelayModal.tsx';
import EditOrderModal, {
  EditOrderModalRef,
} from '@/pages/maintenancePlan/components/EditOrderModal.tsx';

const MaintenancePlan = () => {
  const catchFn = useCatch();
  const { data: alarmTypeOptions } = useQuery({
    queryKey: ['alarmTypeList'],
    queryFn: () => catchFn(() => EventCenterServices.getAlarmTypeList()),
    select: ({ data }) => data.map((item) => ({ label: item, value: item })),
  });

  const { data: deviceOptions } = useQuery({
    queryKey: ['deviceList'],
    queryFn: () => catchFn(() => EventCenterServices.getDeviceList()),
    select: ({ data }) => data.map((item) => ({ label: item.carNo, value: item.carNo })),
  });

  const { data: reporterOptions } = useQuery({
    queryKey: ['reporterList'],
    queryFn: () => catchFn(() => OrderServices.getReporterList()),
    select: ({ data }) => data.map((item) => ({ label: item.name, value: item.id })),
  });

  const tableProps: ITableProps<
    MaintenancePlanInfo,
    MaintenancePlanListParams & {
      alarmTime: Dayjs;
    }
  > = {
    api: {
      key: ['maintenancePlanList'],
      fn: async (params) => {
        const { data, total } = await MaintenancePlanServices.getList({
          ...params,
          alarmTime: params.alarmTime?.format('YYYY-MM-DD'),
        });
        return {
          data,
          total: total ?? 0,
        };
      },
    },
    columns: [
      {
        title: '病害类型',
        dataIndex: 'alarmDesc',
        width: 120,
      },
      {
        title: '上报位置',
        dataIndex: 'reportPosition',
        ellipsis: true,
        render: (value) => (
          <Tooltip title={value} placement="topLeft">
            {value}
          </Tooltip>
        ),
        width: 240,
      },
      {
        title: '报警设备',
        dataIndex: 'carNo',
        width: 100,
      },
      { title: '报警时间', dataIndex: 'alarmTime', width: 200 },
      {
        title: '上报部门',
        dataIndex: 'reportName',
        ellipsis: true,
        render: (value) => <Tooltip title={value}>{value}</Tooltip>,
        width: 150,
      },
      {
        title: '处置状态',
        dataIndex: 'dealWithStatus',
        width: 120,
        render: (value: MaintenancePlanInfo['dealWithStatus']) =>
          MaintenancePlanHandleStatus[value],
      },
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width: 200,
        render: (_value, record) => {
          return (
            <Space size={0} onClick={(e) => e.stopPropagation()}>
              {record.dealWithStatus === 'DEAL_WITH' ? null : record.dealWithStatus ===
                'UNDER_DISPOSAL' ? (
                <PermissionGuard permissions={['CURE_PLAN_UPDATE']}>
                  <Button
                    size="small"
                    type="link"
                    onClick={() =>
                      editOrderModalRef.current?.open({
                        id: record.workOrderId,
                        alarmId: record.alarmId,
                        reportId: record.id,
                      })
                    }
                  >
                    修改工单
                  </Button>
                </PermissionGuard>
              ) : (
                <PermissionGuard permissions={['CURE_PLAN_SAVE']}>
                  <Button
                    size="small"
                    type="link"
                    onClick={() =>
                      editOrderModalRef.current?.open({
                        alarmId: record.alarmId,
                        reportId: record.id,
                      })
                    }
                  >
                    创建工单
                  </Button>
                </PermissionGuard>
              )}
              {record.dealWithStatus === 'DEAL_WITH' ||
              record.dealWithStatus === 'UNDER_DISPOSAL' ? null : (
                <PermissionGuard permissions={['CURE_PLAN_DELAY']}>
                  <Button
                    size="small"
                    type="link"
                    onClick={() => delayModalRef.current?.open(record.id)}
                  >
                    延期处理
                  </Button>
                </PermissionGuard>
              )}
            </Space>
          );
        },
      },
    ],
    onRow: (record) => ({
      onClick: () => {
        drawerRef.current?.open(record.id);
      },
    }),
    fields: [
      {
        name: 'alarmDesc',
        label: '病害类型',
        type: FormFieldType.Select,
        fieldProps: {
          options: alarmTypeOptions,
        },
      },
      {
        name: 'carNoList',
        label: '报警设备',
        type: FormFieldType.Select,
        fieldProps: {
          options: deviceOptions,
        },
      },
      {
        name: 'alarmTime',
        label: '报警时间',
        type: FormFieldType.Date,
      },
      {
        name: 'departmentId',
        label: '上报部门',
        type: FormFieldType.Select,
        fieldProps: {
          options: reporterOptions,
        },
      },
      {
        name: 'reportPosition',
        label: '上报位置',
        type: FormFieldType.Input,
      },
      {
        name: 'dealWithStatus',
        label: '处置状态',
        type: FormFieldType.Select,
        fieldProps: {
          options: Object.entries(MaintenancePlanHandleStatus).map(([key, value]) => ({
            label: value,
            value: key,
          })),
        },
      },
    ],
    rowKey: 'id',
  };

  const tableRef = useRef<ITableRef>(null);

  const drawerRef = useRef<DetailDrawerRef>(null);

  const editOrderModalRef = useRef<EditOrderModalRef>(null);
  const delayModalRef = useRef<DelayModalRef>(null);

  return (
    <>
      <ITable {...tableProps} ref={tableRef} />
      <DetailDrawer ref={drawerRef} />
      <EditOrderModal callback={() => tableRef.current?.refetch()} ref={editOrderModalRef} />
      <DelayModal ref={delayModalRef} onSuccess={() => tableRef.current?.refetch()} />
    </>
  );
};

export default MaintenancePlan;
